package me
import grails.converters.JSON
import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
import groovy.sql.Sql
import groovy.json.*
import groovy.json.JsonSlurper

class ChartthemeController {

	def dataSource

	def store() {
  		def sql = new Sql(dataSource)
   		def results = [:]	  
    	def rows = sql.rows("select * from chart_theme")
    	results.total = rows.size()
    	results = [success:true,total:rows.size(),results:rows]
    	render results as JSON
  	}

	
  	def delete() {
  		def ct = ChartTheme.findById(params.id)
  		println ct
  		ct.delete(flush: true) 
  		def results = [success:true]
    	render results as JSON
  	}

    def save() {
 		def sql = new Sql(dataSource)
   		def resuls = [code:0,message:'success']
   		def themeId = params.themeId
      	def themeName = params.themeName
      	def themeSource = params.themeSource
      	def themeConfigSource = params.themeConfigSource
   		if (themeId==null || themeId=="") {
          def chartTheme = new ChartTheme(themeName: themeName, themeSource: themeSource, themeConfigSource: themeConfigSource)
	       chartTheme.save(failOnError: true)
   			
   		} else {
   			  def chartTheme = ChartTheme.findById(params.themeId)
          try {
              chartTheme.themeName = themeName
              chartTheme.themeSource = themeSource
              chartTheme.themeConfigSource = themeConfigSource
              chartTheme.save(failOnError:true,flush:true) 
          } catch (e) {
              println e
          }

   		}
    	
    	render resuls as JSON
    }

    def design() {
      def chartTheme = [:]
      if (params.id!=null) {
        chartTheme = ChartTheme.findById(params.id)
      }
      
      [chartTheme:chartTheme,chartThemeSource:JsonOutput.toJson(chartTheme.themeSource)]

    }
   	
}
